# -*- coding: UTF-8 -*-

import nltk

Pretraitement_Ponc = {".":" .", ",":" ,"}
Pretraitement_Fr = {"ç":"c","é":"e","è":"e","ê":"e","à":"?a"}
Pretraitement = {
    "bouche ensanglante": "boucheensanglante",
    "doigts noir": "doigtsnoir",
    "yeux ensanglantes": "yeuxensanglantes",
    "trous d aiguilles": "trousdaiguilles",
    "nez ensanglante" : "nezensanglante",
    "a l air": "alair",
    "a paye": "apaye",
    "n aime pas": "naimepas",
    "aime bien": "aime"
    }
###############################################################
##
## Version 2.0.* de NLTK
##
###############################################################

#     NOTE: Le trait sémantique doit être écrit en majuscule "SEM" dans la grammaire

def writefact(file, fact):
    file.write("\n\t" + fact + "\n")
    pass

def writecomment(file, comment):
    file.write("\n\t; " + comment)
    pass

def createfact(file, name):
    file.write("(deffacts " + name + " \n")
    pass

def closefact(file):
    file.write(")\n\n")
    pass

def fcfgToJess(file,str):
    tab = str.replace(',',' ').split('(')
    if len(tab) == 2:
       if tab[0] == 'est':
           writefact(file, '(' + tab[0] + '_' + tab[1])
       else:
           writefact(file, '(' + tab[0] + ' ' + tab[1])
    pass

with open("text.txt") as f:
    sentences = f.readlines()
    
file = open("jess.clp", "w")
file.write("(clear)\n\n")
createfact(file,'fact1')

for sentence in sentences:
    originalSentence = sentence.replace("\n","");
    writecomment(file, originalSentence)
    sentence = sentence.replace("'"," ")
    sentence = sentence.replace("\n","")
    for key, value in Pretraitement_Ponc.items():
        sentence = sentence.replace(key,value)
    for key, value in Pretraitement_Fr.items():
        sentence = sentence.replace(key,value)    
    for key, value in Pretraitement.items():
        sentence = sentence.replace(key,value)
    try:  
        allresults = nltk.batch_interpret([sentence], 'file:Lab2.fcfg')
        if allresults[0]:
            print allresults[0][0][0].node['SEM']
            fcfgToJess(file, str(allresults[0][0][0].node['SEM']))
        else:
            print 'erreur dans la phrase: '+ originalSentence +'(' + sentence +')'
    except Exception, e:
        print 'erreur dans la grammaire:'
        print e
closefact(file)

print "fichier jess créer: jess.clp"

